<?php

namespace App\V3\V3_2_7\Controllers;

use App\V3\V3_2_7\Models\MaterielClassModel;
use App\V3\V3_2_7\Models\MaterielModel;
use App\V3\V3_2_7\Models\MaterielProductContentModel;
use App\V3\V3_2_7\Models\MaterielTypeModel;
use App\V3\V3_2_7\Models\SerialNumberModel;
use App\V3\V3_2_7\Models\StorageBatchModel;
use App\V3\V3_2_7\Models\StorageManageModel;
use App\V3\V3_2_7\Models\TallyClassModel;
use App\V3\V3_2_7\Models\TallyModel;
use App\V3\V3_2_7\Services\CheckStorageManageService;
use App\V3\V3_2_7\Services\MaterielService;
use App\V3\V3_2_7\Services\MaterielTypeService;
use App\V3\V3_2_7\Services\OverflowBreakageService;
use App\V3\V3_2_7\Services\ProductService;
use App\V3\V3_2_7\Services\SalesReturnService;
use App\V3\V3_2_7\Services\SellService;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use App\V3\V3_2_7\Services\StorageManageService;
use Illuminate\Validation\Rule;
use Milon\Barcode\DNS1D;

class CommonDetailController extends Controller
{
    //销售单详细-without token
    public function sellFind(Request $request)
    {
        //参数验证
        $validator = Validator::make($request->except('role_id'), [
            'id' => 'required|integer',//销售单主键id
        ]);

        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }

        return response()->json(SellService::detail($request->id));
    }

    //退货单详细-without token
    public function salesReturnFind(Request $request)
    {
        //参数验证
        $validator = Validator::make($request->except('role_id'), [
            'id' => 'required|integer',//销售单主键id
        ], [
            'id.required' => '退货单id缺失'
        ]);

        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }

        return response()->json(SalesReturnService::find($request->id));
    }

    /**
     * @采购单详细 without token
     * @created 在 2021/12/9 13:52 创建
     * @param Request $request
     * @author: Sun Wu
     */
    public function materielDetail(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->input(), [
            'id' => 'required|integer',//采购单id
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }

        return success(MaterielService::detail($data));
    }

    public function productDetail(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->input(), [
            'id' => 'required|integer',//采购单id
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }

        $detail = ProductService::detail($data['id']);

        if (empty($detail)) {
            return response()->json(['code' => 1, 'msg' => '目标单据信息不存在，请刷新后重试', 'data' => '']);
        }
        $detail = json_decode($detail,true);
        if(!empty($detail['slave_info'])){
            foreach ($detail['slave_info'] as &$sVal){
                if(!empty($detail['slave_content'])){
                    foreach ($detail['slave_content'] as $cVal){
                        $cVal['product_slave_id'] = $sVal['id'];
                        if(!empty($sVal['is_product_materiel'])){
                            $contentId = MaterielProductContentModel::where([
                                'product_id' => $sVal['type_id'],
                                'type_id' =>$cVal['type_id']
                            ])->value('type_id');
                            if(!empty($contentId)){
                                $sVal['product_slave_content'][] = $cVal;
                            }
                        }elseif($sVal['type_id'] == $cVal['type_id']){
                            $sVal['product_slave_content'][] = $cVal;
                        }else{
                            $sVal['product_slave_content'] = [];
                        }
                    }
                }
            }
        }

        return response()->json(['code' => 0, 'msg' => 'success', 'data' => $detail]);
    }

    public function readGoodsIdInfo(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'goods_id' => 'required|integer',//销售单主键id
        ], [
            'goods_id.required' => '商品id缺失'
        ]);

        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }

        return success(StorageManageService::readGoodsIdInfo($data));
    }

    public function classDetail(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'class_id' => 'required|integer',//分类主键id
            'class_type' => [
                'required',
                Rule::in([1, 2])
            ]
        ], [
            'class_id.required' => '分类id缺失',
            'class_id.integer' => '分类id,只能为整数',
            'class_type.required' => '分类类型缺失',
            'class_type.in' => '分类类型错误,1：是一级、2：是二级'
        ]);

        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }
        if ($data['class_type'] == 1) {
            $firClassInfo = MaterielClassModel::query()
                ->select(
                    'id',
                    'class_name',
                    'class_no'
                )->where([
                    'id' => $data['class_id'],
                    'parent_id' => 0,
                    'delete_flag' => 0
                ])->first();
            if (empty($firClassInfo)) return fail('', '无一级分类信息');
            $secClassList = MaterielClassModel::query()
                ->select(
                    'a.id as firCalssId',
                    'a.class_name as firClassName',
                    'a.class_no as firClassNo',
                    'b.id as secClassId',
                    'b.class_name as secClassName',
                    'b.class_no as secClassNo'
                )
                ->from('materiel_class as a')
                ->leftJoin('materiel_class as b', 'b.parent_id', '=', 'a.id')
                ->where([
                    'a.id' => $data['class_id'],
                    'b.delete_flag' => 0
                ])->get();
            if (empty($secClassList->toArray())) return fail('', '无二级分类信息');
            foreach ($secClassList as &$val) {
                $goodsList = MaterielTypeModel::query()
                    ->select(
                        'id',
                        'materiel_name',
                        'materiel_no',
                        'type_name',
                        'is_product_materiel'
                    )->where([
                        'materiel_class_id' => $val['secClassId'],
                        'delete_flag' => 0
                    ])->get();
                if(!empty($goodsList->toArray())){
                    $goodsList = $goodsList->toArray();
                    foreach($goodsList as &$gVal){
                        $gVal['in_storage_num'] = StorageManageModel::query()
                            ->where([
                            'type_id' => $gVal['id'],
                            'delete_flag'=> 0,
                        ])->sum('in_storage_num');
                    }
                }
                $val['goods_list'] = $goodsList;
            }
            $firClassInfo['sec_class_list'] = $secClassList;

        } elseif ($data['class_type'] == 2) {
            $classList = MaterielClassModel::query()
                ->select(
                    'a.id as firCalssId',
                    'a.class_name as firClassName',
                    'a.class_no as firClassNo',
                    'b.id as secClassId',
                    'b.class_name as secClassName',
                    'b.class_no as secClassNo'
                )
                ->from('materiel_class as a')
                ->leftJoin('materiel_class as b', 'b.parent_id', '=', 'a.id')
                ->where([
                    'b.id' => $data['class_id'],
                    'b.delete_flag' => 0
                ])->first();
            if (empty($classList)) return fail('', '无二级分类信息');
            $firClassInfo = [
                'id' => $classList['firCalssId'],
                'class_name' => $classList['firClassName'],
                'class_no' => $classList['firClassNo'],
                'secClassId' => $classList['secClassId'],
                'secClassName' => $classList['secClassName'],
                'secClassNo' => $classList['secClassNo'],
            ];

            $goodsList = MaterielTypeModel::query()
                ->select(
                    'id',
                    'materiel_name',
                    'materiel_no',
                    'type_name',
                    'is_product_materiel'
                )->where([
                    'materiel_class_id' => $classList['secClassId'],
                    'delete_flag' => 0
                ])->get();
            if(!empty($goodsList->toArray())){
                $goodsList = $goodsList->toArray();
                foreach($goodsList as &$gVal){
                    $gVal['in_storage_num'] = StorageManageModel::query()
                        ->where([
                            'type_id' => $gVal['id'],
                            'delete_flag'=> 0,
                        ])->sum('in_storage_num');
                }
            }
            $classList['goods_list'] = $goodsList;
            $firClassInfo['sec_class_list'][] = $classList;

        }
        return success($firClassInfo);
    }

    public function inventoryDetail(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'storage_manage_id' => 'required|integer',//库存主键id
        ], [
            'storage_manage_id.required' => '库存id缺失',
            'storage_manage_id.integer' => '库存id，必有为整数'
        ]);

        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }

        return success(StorageManageService::inventoryDetail($data));

    }

    /**
     *盘点（H5）
     * Author: zlf
     * Created at 2024/5/22 9:58
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getCheckGoodsList(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'check_no' => 'required',//盘点编号
        ], [
            'check_no.required' => '`盘点编号`必要参数',
        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return fail('', $info);
        }
        $condition = [];
        $keyword = empty($request->keyword) ? '' : $request->keyword;
        $list = CheckStorageManageService::checkSkGoodsList($condition, $data, $keyword);

        if (!empty($list['data'])) {
            foreach ($list['data'] as $k => $v) {
                $list['data'][$k]['shelf_name'] = !empty($v['shelf_name']) ? $v['shelf_name'] : "";
                $list['data'][$k]['location_name'] = !empty($v['location_name']) ? $v['location_name'] : "";
                if ($v['is_cover'] == 1) {
                    if ($v['yk_flag'] == 2) {
                        $list['data'][$k]['in_storage_num'] = $v['check_num'] + $v['yk_num'];
                    } elseif ($v['yk_flag'] == 1) {
                        $list['data'][$k]['in_storage_num'] = $v['check_num'] - $v['yk_num'];
                    }
                }
            }
        }
        return success($list);
    }

    /**
     *记账（H5）
     * Author: zlf
     * Created at 2024/5/22 10:37
     * @param Request $request
     * @return mixed
     */
    public function getTallyFind(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'id' => 'required|integer',//记账分类主键id
        ], [
            'id.required' => '记账标识id缺失',
            'id.integer' => '记账标识id仅能为数字',
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return fail('', $info);
        }
        $model = TallyModel::find($data['id']);
        $model['tally_class_name'] = TallyClassModel::query()
            ->where(['id' => $model['tally_class_id']])
            ->value('name') ?? $model['tally_class_name'];
        return success($model);

    }

    /**
     *批次列表（H5）
     * Author: zlf
     * Created at 2024/5/22 15:06
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getBatchInfo(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'batch_no' => 'required',//页面大小
        ], [
            'batch_no.required' => '参数`批次主键id`缺失',

        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return fail('', $info);
        }
        $id = StorageBatchModel::query()->where(['batch_no' => $data['batch_no']])->value('id');
        $result = StorageManageService::batchMaterielInfo($id);
        if (!empty($result['upload_credentials_img'])) {
            $result['upload_credentials_img'] = preg_split("/,/", $result['upload_credentials_img']);
        } else {
            $result['upload_credentials_img'] = [];
        }
        // 生成PNG格式的条形码并保存到服务器
        if(!empty($result['bar_code'])){
            $DNS1D = new DNS1D();
            $resl = $DNS1D->getBarcodePNG($result['bar_code'], 'C128A');
            $result['bar_code_img'] = $resl??"";
        }
        $oneDay = 24 * 3600;
        $result['expire_flag'] = 0;
        if (!empty($result['production_time'])) {
            if (!empty($result['expiration_date'])) {//保质期
                $expirationDate = $result['expiration_date'] * $oneDay;//保质期的时间戳
                $expirationTime = strtotime($result['production_time']) + $expirationDate;//过期时间的时间戳
                $timeRemaining = $expirationTime - time();//剩余时间
                if (!empty($result['warning_time']) && $timeRemaining > 0) {//预警时间设置
                    $day = $timeRemaining / $oneDay;//剩余天数
                    if ($day <= $result['warning_time']) {
                        $result['expire_flag'] = 1;
                    }
                } elseif ($timeRemaining <= 0) {
                    $result['expire_flag'] = 1;
                }
            }
        }

        if (!empty(strtotime($result['production_time'])) && !empty($result['warning_time']) && !empty($result['expiration_date'])) {
            $warningTime = strtotime($result['production_time']) + ($result['expiration_date'] - $result['warning_time']) * 3600;
            $result['warning_time'] = date('Y-m-d H:i:s', $warningTime);
        }

        return success($result);
    }

    /**
     *序列号详情（H5）
     * Author: zlf
     * Created at 2024/5/22 16:14
     * @param Request $request
     * @return void
     */
    public function getSerialNumberInfo(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'serialId' => 'required|integer',//序列号主键id
        ], [
            'serialId.required' => '参数`序列号主键id`缺失',
            'serialId.integer' => '参数`序列号主键id`仅能为数字',
        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return fail('', $info);
        }
        return success(StorageManageService::getSerialNumberInfo($data));
    }

    /**
     *库位详情(H5)
     * Author: zlf
     * Created at 2024/5/23 11:14
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getStorageLocationInfo(Request $request)
    {
        $data = $request->all();
        return success(StorageManageService::getStorageLocationInfo($data));
    }

    public function getGoodsDetail(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'goods_id' => 'required',//库位主键id
        ], [
            'goods_id.required' => '参数`商品主键id`缺失',
        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return fail('', $info);
        }
        if(strpos($data['goods_id'],'smycg') !== false){
            $data['goods_id'] = explode('smycg',$data['goods_id'])[1];
        }
        return success(MaterielTypeService::getGoodsDetail($data));
    }
}
